package com.aiyige.page.filter.adapter;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.eventbus.EventSelectLocation;
import com.aiyige.model.commontag.CommonTag;
import com.aiyige.model.commontag.util.CommonTagUtil;
import com.aiyige.page.filter.model.Filter;
import com.aiyige.page.filter.util.FilterUtil;
import com.aiyige.utils.ColorUtil;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FilterAdapter extends BaseQuickAdapter<Filter, BaseViewHolder> {
    FragmentActivity activity;

    public FilterAdapter(FragmentActivity activity) {
        super(new LinkedList<Filter>());
        this.activity = activity;
    }

    @Override
    protected void convert(BaseViewHolder helper, Filter item) {
        switch (item.getType()) {
            case Filter.TYPE_ADDRESS:
                ((AddressFilterGroupVH) helper).bindData(item);
                break;
            case Filter.TYPE_MULTI_SELECT_BIG_RECT:
                ((MultiSelectBigGridFilterGroupVH) helper).bindData(item);
                break;
            case Filter.TYPE_MULTI_SELECT_SMALL_RECT:
                ((MultiSelectSmallGridFilterGroupVH) helper).bindData(item);
                break;
            case Filter.TYPE_SINGLE_SELECT_BIG_RECT:
                ((SingleSelectBigGridFilterGroupVH) helper).bindData(item);
                break;
            case Filter.TYPE_SINGLE_SELECT_SMALL_RECT:
                ((SingleSelectSmallGridFilterGroupVH) helper).bindData(item);
                break;
            case Filter.TYPE_TIME_RANGE:
                ((TimeRangeFilterGroupVH) helper).bindData(item);
                break;
        }
    }

    @Override
    protected BaseViewHolder onCreateDefViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder;
        switch (viewType) {
            case Filter.TYPE_ADDRESS:
                baseViewHolder = new AddressFilterGroupVH(getItemView(R.layout.address_filter_group, parent));
                break;
            case Filter.TYPE_MULTI_SELECT_BIG_RECT:
                baseViewHolder = new MultiSelectBigGridFilterGroupVH(getItemView(R.layout.grid_filter_group, parent));
                break;
            case Filter.TYPE_MULTI_SELECT_SMALL_RECT:
                baseViewHolder = new MultiSelectSmallGridFilterGroupVH(getItemView(R.layout.grid_filter_group, parent));
                break;
            case Filter.TYPE_SINGLE_SELECT_BIG_RECT:
                baseViewHolder = new SingleSelectBigGridFilterGroupVH(getItemView(R.layout.grid_filter_group, parent));
                break;
            case Filter.TYPE_SINGLE_SELECT_SMALL_RECT:
                baseViewHolder = new SingleSelectSmallGridFilterGroupVH(getItemView(R.layout.grid_filter_group, parent));
                break;
            case Filter.TYPE_TIME_RANGE:
                baseViewHolder = new TimeRangeFilterGroupVH(getItemView(R.layout.time_range_filter_group, parent));
                break;
            default:
                baseViewHolder = new BaseViewHolder(getItemView(R.layout.wild_card_item, parent));
                break;
        }
        return baseViewHolder;
    }


    @Override
    protected int getDefItemViewType(int position) {
        return getItem(position).getType();
    }


    public class MultiSelectSmallGridFilterGroupVH extends BaseViewHolder {
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.groupRv)
        RecyclerView groupRv;
        SmallGridFilterGroupAdapter adapter;
        Filter data;

        public MultiSelectSmallGridFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
            adapter = new SmallGridFilterGroupAdapter();
            groupRv.setLayoutManager(new GridLayoutManager(itemView.getContext(), 4));
            adapter.bindToRecyclerView(groupRv);
            groupRv.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    int index = parent.getChildAdapterPosition(view);
                    if (index < 4) {
                        outRect.set(UIHelper.dip2px(5), 0, UIHelper.dip2px(5), 0);
                    } else {
                        outRect.set(UIHelper.dip2px(5), UIHelper.dip2px(10), UIHelper.dip2px(5), 0);
                    }
                }
            });
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    CommonTag commonTag = adapter.getItem(position);
                    if (!commonTag.isSelected() && CommonTagUtil.countOfSelected(adapter.getData()) >= FilterUtil.MAX_MULTI_SELECT_NUM) {
                        ToastX.show(StringUtils.getString(R.string.reach_max_selected_filter_num, FilterUtil.MAX_MULTI_SELECT_NUM));
                        return;
                    }
                    commonTag.setSelected(!commonTag.isSelected());
                    adapter.setData(position, commonTag);
                }
            });
            groupRv.setNestedScrollingEnabled(false);
        }

        public void bindData(Filter filter) {
            data = filter;
            adapter.setNewData(data.getTagList());
            groupTitleTv.setText(data.getName());
        }

    }

    public class SingleSelectSmallGridFilterGroupVH extends BaseViewHolder {
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.groupRv)
        RecyclerView groupRv;
        SmallGridFilterGroupAdapter adapter;
        Filter data;

        public SingleSelectSmallGridFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
            adapter = new SmallGridFilterGroupAdapter();
            groupRv.setLayoutManager(new GridLayoutManager(itemView.getContext(), 4));
            adapter.bindToRecyclerView(groupRv);
            groupRv.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    int index = parent.getChildAdapterPosition(view);
                    if (index < 4) {
                        outRect.set(UIHelper.dip2px(5), 0, UIHelper.dip2px(5), 0);
                    } else {
                        outRect.set(UIHelper.dip2px(5), UIHelper.dip2px(10), UIHelper.dip2px(5), 0);
                    }
                }
            });
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    CommonTag commonTag = adapter.getItem(position);
                    if (commonTag.isSelected()) {
                        commonTag.setSelected(false);
                    } else {
                        for (int i = 0; i < adapter.getData().size(); ++i) {
                            if (adapter.getItem(i).isSelected()) {
                                CommonTag previousSelected = adapter.getItem(i);
                                previousSelected.setSelected(false);
                                adapter.setData(i, previousSelected);
                                break;
                            }
                        }
                        commonTag.setSelected(true);
                    }
                    adapter.setData(position, commonTag);
                }
            });
            groupRv.setNestedScrollingEnabled(false);
        }

        public void bindData(Filter filter) {
            data = filter;
            groupTitleTv.setText(data.getName());
            adapter.setNewData(data.getTagList());
        }
    }


    public class MultiSelectBigGridFilterGroupVH extends BaseViewHolder {
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.groupRv)
        RecyclerView groupRv;
        BigGridFilterGroupAdapter adapter;
        Filter data;

        public MultiSelectBigGridFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
            adapter = new BigGridFilterGroupAdapter();
            groupRv.setLayoutManager(new GridLayoutManager(itemView.getContext(), 3));
            adapter.bindToRecyclerView(groupRv);
            groupRv.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    int index = parent.getChildAdapterPosition(view);
                    if (index < 3) {
                        outRect.set(UIHelper.dip2px(5), 0, UIHelper.dip2px(5), 0);
                    } else {
                        outRect.set(UIHelper.dip2px(5), UIHelper.dip2px(10), UIHelper.dip2px(5), 0);
                    }
                }
            });
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    CommonTag commonTag = adapter.getItem(position);
                    if (!commonTag.isSelected() && CommonTagUtil.countOfSelected(adapter.getData()) >= FilterUtil.MAX_MULTI_SELECT_NUM) {
                        ToastX.show(StringUtils.getString(R.string.reach_max_selected_filter_num, FilterUtil.MAX_MULTI_SELECT_NUM));
                        return;
                    }
                    commonTag.setSelected(!commonTag.isSelected());
                    adapter.setData(position, commonTag);
                }
            });
            groupRv.setNestedScrollingEnabled(false);
        }

        public void bindData(Filter filter) {
            data = filter;
            groupTitleTv.setText(data.getName());
            adapter.setNewData(data.getTagList());
        }
    }

    public class SingleSelectBigGridFilterGroupVH extends BaseViewHolder {
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.groupRv)
        RecyclerView groupRv;
        BigGridFilterGroupAdapter adapter;
        Filter data;

        public SingleSelectBigGridFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
            adapter = new BigGridFilterGroupAdapter();
            groupRv.setLayoutManager(new GridLayoutManager(itemView.getContext(), 3));
            adapter.bindToRecyclerView(groupRv);
            groupRv.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    int index = parent.getChildAdapterPosition(view);
                    if (index < 3) {
                        outRect.set(UIHelper.dip2px(5), 0, UIHelper.dip2px(5), 0);
                    } else {
                        outRect.set(UIHelper.dip2px(5), UIHelper.dip2px(10), UIHelper.dip2px(5), 0);
                    }
                }
            });
            adapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    CommonTag commonTag = adapter.getItem(position);
                    if (commonTag.isSelected()) {
                        commonTag.setSelected(false);
                    } else {
                        for (int i = 0; i < adapter.getData().size(); ++i) {
                            if (adapter.getItem(i).isSelected()) {
                                CommonTag previousSelected = adapter.getItem(i);
                                previousSelected.setSelected(false);
                                adapter.setData(i, previousSelected);
                                break;
                            }
                        }
                        commonTag.setSelected(true);
                    }
                    adapter.setData(position, commonTag);
                }
            });
            groupRv.setNestedScrollingEnabled(false);
        }

        public void bindData(Filter filter) {
            data = filter;
            groupTitleTv.setText(filter.getName());
            adapter.setNewData(filter.getTagList());
        }
    }

    public class TimeRangeFilterGroupVH extends BaseViewHolder {
        Filter data;
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.startTimeTv)
        TextView startTimeTv;
        @BindView(R.id.endTimeTv)
        TextView endTimeTv;

        public TimeRangeFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(Filter filter) {
            data = filter;
            groupTitleTv.setText(data.getName());
            if (filter.getStartTime() != null) {
                startTimeTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", filter.getStartTime()));
            } else {
                startTimeTv.setText("");
            }
            if (filter.getEndTime() != null) {
                endTimeTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", filter.getEndTime()));
            } else {
                endTimeTv.setText("");
            }
        }

        @OnClick({R.id.startTimeTv, R.id.endTimeTv})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.startTimeTv: {
                    Calendar selectedDate = Calendar.getInstance();
                    if (data.getStartTime() != null) {
                        selectedDate.setTimeInMillis(data.getStartTime());
                    }

                    //时间选择器
                    TimePickerView pickerView = new TimePickerView.Builder(itemView.getContext(), new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {//选中事件回调
                            data.setStartTime(date.getTime());
                            startTimeTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", data.getStartTime()));
                        }
                    })
                            //年月日时分秒 的显示与否，不设置则默认全部显示
                            .setType(new boolean[]{true, true, true, false, false, false})
                            .setSubmitText(StringUtils.getString(R.string.finish))
                            .setTitleBgColor(Color.WHITE)
                            .setBgColor(0xfff0f0f0)
                            .setLabel("", "", "", "", "", "")
                            .isCenterLabel(false)
                            .setDividerColor(Color.DKGRAY)
                            .setContentSize(21)
                            .setDate(selectedDate)
                            .setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_fc9ac1))
                            .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_fc9ac1))
                            .isDialog(true)
                            .build();
                    pickerView.show();
                    break;
                }

                case R.id.endTimeTv: {
                    Calendar selectedDate = Calendar.getInstance();
                    if (data.getEndTime() != null) {
                        selectedDate.setTimeInMillis(data.getEndTime());
                    }

                    //时间选择器
                    TimePickerView pickerView = new TimePickerView.Builder(itemView.getContext(), new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {//选中事件回调
                            data.setEndTime(date.getTime());
                            endTimeTv.setText(DateFormatUtil.formatMS("yyyy-MM-dd", data.getEndTime()));
                        }
                    })
                            //年月日时分秒 的显示与否，不设置则默认全部显示
                            .setType(new boolean[]{true, true, true, false, false, false})
                            .setSubmitText(StringUtils.getString(R.string.finish))
                            .setTitleBgColor(Color.WHITE)
                            .setBgColor(0xfff0f0f0)
                            .setLabel("", "", "", "", "", "")
                            .isCenterLabel(false)
                            .setDividerColor(Color.DKGRAY)
                            .setContentSize(21)
                            .setDate(selectedDate)
                            .setSubmitColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                            .setCancelColor(ColorUtil.getColor(R.color.zwcolor_pink_f93684))
                            .isDialog(true)
                            .build();
                    pickerView.show();
                    break;
                }
            }
        }


    }

    public class AddressFilterGroupVH extends BaseViewHolder {
        @BindView(R.id.groupTitleTv)
        TextView groupTitleTv;
        @BindView(R.id.addressTv)
        TextView addressTv;
        @BindView(R.id.actionLayout)
        LinearLayout actionLayout;
        Filter data;

        public AddressFilterGroupVH(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        public void bindData(Filter filter) {
            data = filter;
            groupTitleTv.setText(filter.getName());
            if (!TextUtils.isEmpty(filter.getCity())) {
                addressTv.setText(filter.getCity());
            } else {
                addressTv.setText("");
            }
        }

        @OnClick({R.id.actionLayout})
        public void onViewClick(View v) {
            switch (v.getId()) {
                case R.id.actionLayout:
                    doSelectLocation();
                    break;
            }
        }

        private void doSelectLocation() {
            registerEventBus();
            ARouter.getInstance()
                    .build(ARouterConfig.SelectLocationPage)
                    .navigation();
        }

        private void registerEventBus() {
            try {
                if (!EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().register(this);
                }
            } catch (Exception e) {

            }
        }

        private void unregisterEventBus() {
            try {
                if (EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().unregister(this);
                }
            } catch (Exception e) {

            }
        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onEvent(EventSelectLocation event) {
            unregisterEventBus();
            if (event.getResultCode() == Activity.RESULT_OK) {
                data.setCity(event.getData().getCity());
                data.setCityId(event.getData().getCityId());
                data.setProvince(event.getData().getProvince());
                bindData(data);
            }
        }
    }
}
